package com.ruoyi.web.controller.tool;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.system.domain.UserCodeRecord;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.UserCodeRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class DeptCode {
    public Map<Long,Integer> map;
    public Map<Long,String> prefix;
    public boolean update;

    @Autowired
    UserCodeRecordMapper mapper;
    @Autowired
    SysDeptMapper deptMapper;

    @PostConstruct
    public void init(){
        prefix=new HashMap<>();
        prefix.put(100L,"SYS");
        prefix.put(200L,"XM");
        prefix.put(201L,"YP");
        prefix.put(202L,"CW");
        prefix.put(203L,"SY");
        prefix.put(204L,"FZR");
        prefix.put(205L,"GL");
        update=false;
        map=new HashMap<>();
        List<UserCodeRecord> all = mapper.getAll();
        for (UserCodeRecord userCodeRecord : all) {
            map.put(userCodeRecord.getDeptId(), userCodeRecord.getCurr());
        }
    }

    private synchronized Integer getCurr(Long dept){
        Integer i = map.get(dept);
        map.put(dept,i+1);
        update=true;
        return i;
    }
    public String getCode(Long dept){
        return prefix.get(dept)+String.format("%05d",getCurr(dept));
    }

    @PreDestroy
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void update(){
        if (update){
            for (Map.Entry<Long, Integer> entry : map.entrySet()) {
                UserCodeRecord record = new UserCodeRecord(entry.getKey(), entry.getValue());
                mapper.updateCurr(record);
            }
        }
    }
}
